package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentRepository repository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(StrategyComment comment) {
        if (comment.getId() == null || "".equals(comment.getId().trim())){
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //拼接条件
        Query query = new Query();
        if (qo.getDetailId() != -1l){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查询总条数
        long count = mongoTemplate.count(query, StrategyComment.class);
        //如果总条数为0，返回空集合
        if (count == 0){
            return Page.empty();
        }
        //查询分页的结果集
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        List<StrategyComment> list = mongoTemplate.find(query, StrategyComment.class);
        return new PageImpl(list,pageable,count);
    }

    @Override
    public void commentThumbUp(String toid, Long fromid) {
        //判断这条评论是否有被当前用户点赞
        StrategyComment strategyComment = repository.findById(toid).get();
        List<Long> thumbuplist = strategyComment.getThumbuplist();
        //如果用户ID不在点赞用户集合中，执行点赞操作，点赞数加一，点赞集合加上当前用户ID
        if (!thumbuplist.contains(fromid)){
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
            thumbuplist.add(fromid);
            strategyComment.setThumbuplist(thumbuplist);
        }else{
            //如果用户ID在点赞用户集合中，执行取消点赞操作，点赞数减一，点赞集合移除当前用户ID
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
            thumbuplist.remove(fromid);
            strategyComment.setThumbuplist(thumbuplist);
        }
        repository.save(strategyComment);
    }
}
